package com.by.service;

import com.by.mapper.UserMapper;
import com.by.pojo.Permission;
import com.by.pojo.Role;
import com.by.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //username 前台输入框拿的
        //password 后台数据库拿的

        //根据username查询user
        User user = userMapper.getUserByUserName(username);
        if (user == null) {
            return null;
        }

        //提供密码
        String password = user.getPassword();


        //提供权限
        List<GrantedAuthority> gaList = new ArrayList<>();
        Set<Role> roleSet = user.getRoles();
        for (Role role : roleSet) {
            //t_role keyword 角色类型
            gaList.add(new SimpleGrantedAuthority(role.getKeyword()));
            //权限--->按钮---->功能
            Set<Permission> permissionSet = role.getPermissions();
            for (Permission permission : permissionSet) {
                //t_permission keyword 权限类型
                gaList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }


        return new org.springframework.security.core.userdetails.User(username, password, gaList);
    }
}
